const app = getApp()
const myRequest = require('../../../utils/request'); // 导入整个模块
import {
  createStoreBindings
} from 'mobx-miniprogram-bindings'
import {
  store
} from '../../../store/strategy/index'
const throttle = (fn, delay) => {
  var startTime = new Date();
  return function () {
    var context = this;
    var args = arguments;
    var endTime = new Date();
    var resTime = endTime - startTime;
    //判断大于等于我们给的时间采取执行函数;
    if (resTime >= delay) {
      fn.apply(context, args);
      //执行完函数之后重置初始时间，等于最后一次触发的时间
      startTime = endTime;
    }
  }
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    strategylist: [],
    valuecity: '',
    showlist: [],
    allList: [],
    index: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getdata()
    //在onload中创建
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['strategy'],
      actions: ['updatestrategy']
    })
  },
  
  replaceSpecialChar(content) {
    var regex = new RegExp('<img', 'gi')
    var delImgStyleReg = /(?<=\" )style=\".*?\"/gi;
    content = content.replace(delImgStyleReg, '')
    content = content.replace(regex, '<img style="width: 100%  !important";height:"auto  !important"')
    return content;

  },
  onChange(e) {
    this.setData({
      valuecity: e.detail,
    });
  },
  onSearch(e) {
    const searchlist = []
    this.data.strategylist.forEach(val => {
      if (val.tag.includes(this.data.valuecity)) {
        searchlist.push(val)
      }
    })
    this.setData({
      showlist: searchlist
    })
    this.settledata()
  },
  onCancel() {
    this.setData({
      valuecity: '',
      showlist: this.data.strategylist
    })
    this.settledata()
  },
  getdata() {
    let that = this
    myRequest.get('/strategy/strategydata', {}).then(res=>{
      let data = []
      res.data.forEach(val => {
        val.collect = JSON.parse(val.collect)
        val.comment = JSON.parse(val.comment)
        val.like = JSON.parse(val.like)
        val.tag = JSON.parse(val.tag)
        val.avatar = app.globalData.baseAPI + val.avatar
        let description = val.content
        description = description
          .replace(/(\n)/g, '')
          .replace(/(\t)/g, '')
          .replace(/(\r)/g, '')
          .replace(/<\/?[^>]*>/g, '')
          .replace(/\s*/g, '')
        val.description = description
      })
      that.setData({
        strategylist: res.data,
        showlist: res.data
      })

      that.settledata()
    })
 
  },
  settledata() {
    // 一个列表为一屏
    this.wholePageIndex = 0 // 整屏索引
    this.wholeAllList = [] // 储存所有屏数组
    this.currentPageIndex = 0 // 当前可视位置的索引
    this.currentRenderIndex = 0; // 当前渲染的索引
    this.allPageHeightList = []; // 储存每一屏的高度
    this.windowHeight = wx.getSystemInfoSync().windowHeight // 可视区域高度
    // 0-19 20 -39 40-46 
    // 当前页数组储存
    this.wholeAllList[this.wholePageIndex] = this.data.showlist.slice(this.wholePageIndex * 20, this.wholePageIndex * 20 + 20);
    // 当前页赋值
    this.setData({
      ['allList[' + this.wholePageIndex + ']']: this.data.showlist.slice(this.wholePageIndex * 20, this.wholePageIndex * 20 + 20)
    }, () => {
      // 获取每屏高度并储存
      this.getWholeInfo()
    })

  },
  getWholeInfo() {
    const that = this
    const wholePageIndex = that.wholePageIndex
    // 此api不能用that
    this.query = this.createSelectorQuery()
    this.query.select(`#wrap_${wholePageIndex}`).boundingClientRect()
    this.query.exec(function (res) {
      // 储存每一屏的高度
      that.allPageHeightList[wholePageIndex] = res[0] && res[0].height;
      console.log("this.allPageHeightList", that.allPageHeightList);
    })
  },
  // 加上节流
  onPageScroll: throttle(function (e) {
    console.log(111);
    const that = this
    const {
      scrollTop
    } = e
    const wholePageIndex = that.wholePageIndex

    // 滚动的时候需要实时去计算当前应该在哪一屏幕
    // 循环获取所有屏总高度
    let allPageHeight = 0
    for (let i = 0; i < that.allPageHeightList.length; i++) {
      allPageHeight = allPageHeight + that.allPageHeightList[i]
      // 判断当前在哪个屏，并跳出，一定要用break
      if (allPageHeight > scrollTop + that.windowHeight) {
        // 获取当前可视位置索引
        that.currentPageIndex = i
        break;
      }
    }

    const currentRenderIndex = that.currentRenderIndex

    //  当时可视位置索引 不等于 当前渲染的索引 时
    // 也就是页面上划时，需要渲染加载之前的数组
    if (that.currentPageIndex !== currentRenderIndex) {
      // 给不渲染的元素占位
      // 设置初始长度 wholePageIndex + 1 长度为 1，将一个固定值替换数组内的元素。
      let blankDivList = new Array(wholePageIndex + 1).fill(0);
      blankDivList.forEach((item, index) => {
        if (that.currentPageIndex - 1 <= index && index <= that.currentPageIndex + 1) {
          blankDivList[index] = that.wholeAllList[index];
        } else {
          blankDivList[index] = {
            height: that.allPageHeightList[index]
          };
        }
      })

      that.currentRenderIndex = that.currentPageIndex;
      // 再重新赋值
      that.setData({
        allList: blankDivList
      })
    }
    console.log(that.data.allList);

  }, 500),
  // 触底加载
  getReachBottomData() {
    if (this.wholePageIndex >= Math.ceil(this.data.showlist.length / 20) - 1) return;
    this.wholePageIndex += 1; // 整屏索引 + 1
    this.currentRenderIndex = this.wholePageIndex; // 当前渲染的索引 + 1

    // 储存下一页的数据
    let nextData = this.data.showlist.slice(this.wholePageIndex * 20, (this.wholePageIndex + 1) * 20);
    if (nextData.length > 0) {
      this.wholeAllList[this.wholePageIndex] = nextData;
      let dataSet = {};
      dataSet['allList[' + this.wholePageIndex + ']'] = nextData;
      this.setData(dataSet, () => {
        this.getWholeInfo();
      });
    } else {
      // 如果没有更多数据，更新allList以移除空白占位
      let blankDivList = this.data.allList.slice(0, this.wholePageIndex + 1);
      this.setData({
        allList: blankDivList
      });
    }
  },

  // 页面下拉触底事件的处理函数
  onReachBottom: function () {
    this.getReachBottomData();
  },

  //攻略详情
  toastrategy(e) {
    const data = e.currentTarget.dataset.item
    data.islove = false
    data.iscollect = false
    let username = JSON.parse(wx.getStorageSync('userinfo')).username
    data.content = this.replaceSpecialChar(data.content)

    data.like.forEach((element, index) => {
      if (username == element.username) {
        data.islove = true
      }
    });
    data.collect.forEach((element, index) => {
      if (username == element.username) {
        data.iscollect = true
      }
    });

    store.updatestrategy(e.currentTarget.dataset.item)
    wx.navigateTo({
      url: '/packagesB/pages/astrategy/index',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },



  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})